<?php 
namespace backend\controllers;
use yii\web\Controller;
use Yii;
use backend\models\TmeInstockinfo;
use backend\models\TmeInstockdetailsinfo;
use backend\models\PurchaseForm;
use yii\base\Exception;
use backend\models\TbaSupplierinfo;
use backend\extention_class;
use backend\extention_class\zhuji;
use yii\db\Query;
use backend\controllers\RbacController;
use backend\models\TauOperinfo;
use backend\models\TmeMerchandiseinfo;
use yii\helpers\ArrayHelper;


/**
 * #name=入库管理#
 * @author Administrator
 */
class PurchaseController extends RbacController {	

	public $layout = 'ace';//定义，默认模板		

	/**
	 * #operation=库存列表#
	 */
	public function actionIndex(){		
		$model = new PurchaseForm(['scenario'=>'add']);
		
		return $this->render('_purchaseinto');	
	}
	
	/**
	 *#operation=添加供应商#
	 */
	public function actionSupplier(){
		//异步获取供应商名称助记码
		if(yii::$app->request->post('action') =='supplierab'){
			$name = yii::$app->request->post('name');
			$suppliername = new zhuji();
			$suppliername = strtolower($suppliername->getInitials($name));
			echo $suppliername;exit;
		}
		$supplierModel = new PurchaseForm(['scenario'=>'addsupplier']);
		if(yii::$app->request->isPost && 'addsupplier' == yii::$app->request->post('action')){
			$supplierModel->attributes = yii::$app->request->post('PurchaseForm');
			if($supplierModel->validate()){
				$supplierinto = new TbaSupplierinfo();
				$supplierinto->attributes = $supplierModel->attributes;
				if($supplierinto->save())																//执行写入数据库操作
					$this->redirect(['purchase/supplier']);
				else 
					echo ("<script>alert('失败');window.history.go(-1);</script>");
			}						
		}
		return $this->render('supplier',[
				'supplierModel'=>$supplierModel,
		]);
	}
	
	/**
	 * #operation=供应商列表异步获取数据#
	 */
	public function actionSupplierlist(){
		$start = yii::$app->request->post('start');							//开始的条数
		$length = yii::$app->request->post('length');						//显示的条数
		$column = yii::$app->request->post('order')[0]['column'];			//排序的字段
		$dir = yii::$app->request->post('order')[0]['dir'];					//正序倒叙
		$draw = yii::$app->request->post('draw');							//页数
		$search = yii::$app->request->post('search')['value'];
		
		//允许排序的列
		$columNameArray = [
			'1'=>'id',
			'2'=>'supplierid',
			'4'=>'supplierab',
			'5'=>'address',
			'6'=>'linkname',
			'10'=>'state'
		];
		$columnName = $columNameArray[$column];
		//搜索正则
		if($search)
			$where = "id like '%".$search."%' or supplierid like '%".$search."%' or linkname like '%".$search."%'
					  or address like '%".$search."%' or QQ like '%".$search."%' or linktel like '%".$search."%' or email like '%".$search."%'";
		else
			$where = '';
		//查询数据库数据
		$model = TbaSupplierinfo::find()->where($where)->orderBy($columnName." ".$dir)->limit($length)->offset($start)->all();
		$total = TbaSupplierinfo::find()->where($where)->count();
		$filetotal = TbaSupplierinfo::find()->count();											//计算数据总数

		$data = [];
		foreach($model as $v){
			$temp = [];
			$temp['chose']='<td ><label class="pos-rel" style="width:100px;text-align:center"> <input type="checkbox"class="ace" /> <span class="lbl"></span></label></td>';	
			$temp['id']=$v['id'];
			$temp['supplierid'] = $v['supplierid'];
			$temp['suppliername'] = $v['suppliername'];
			$temp['supplierab'] = $v['supplierab'];
			$temp['address'] = $v['address'];
			$temp['linkname'] = $v['linkname'];
			$temp['linktel'] = $v['linktel'];
			$temp['qq'] = $v['qq'];
			$temp['email'] = $v['email'];
			if($v['state'] == 1)
				$state = "启用";
			elseif($v['state'] == 0)
				$state = "未启用";
			$temp['state'] = $state;
			$temp['options']='<div class="hidden-sm hidden-xs action-buttons">
							<a class="blue" href="#" onclick="return view('.$v['id'].')">
								<i class="ace-icon fa fa-search-plus bigger-130"></i>
							</a>
							<a class="green" href="#" onclick="return update('.$v['id'].')">
								<i class="ace-icon fa fa-pencil bigger-130"></i>
							</a>
							<a class="red"  onclick="return supplierdelete('.$v['id'].')" href="#">
								<i class="ace-icon fa fa-trash-o bigger-130"></i>
							</a>				
						</div>';
			$data[] = $temp;
		}
		
		$temp = [
		 	'draw'=>$draw,																				//页数
		 	'recordsTotal'=>$filetotal,																		//表的总记录数
		 	'recordsFiltered'=>$total,  																//条件过滤后记录数
		 	'data'=>$data	
 		];
		echo json_encode($temp);
	}
	/**
	 * #operation=供应商列表查看#
	 */
	public function actionSupplierview(){
		$id = yii::$app->request->post('id');
		$info = TbaSupplierinfo::findOne($id);
		echo "<div style=\"font-size:14px;line-height:30px;\"><br/>";
		echo "<div style=\" float:left\">供应商编号：" . $info->supplierid . "</div>";
		echo "<div style=\" margin-left:200px \">供应商名称：" .$info->suppliername . "</div>";
		echo "<div style=\" float:left\">供应商助记码：".$info->supplierab."</div>";
		echo "<div style=\" margin-left:200px \">地址：".$info->address."</div>";
		echo "</div><div class=\"hr hr-12 hr-double\"></div>";
		echo "<div style=\"font-size:14px;line-height:30px\">联系人信息<br/>";
		echo "<div style=\" float:left\">联系人：" . $info->linkname . "</div>";
		echo "<div style=\" margin-left:200px \">联系电话:" . $info->linktel . "</div>";
		echo "<div style=\" margin-right:200px \">QQ：" . $info->qq. "</div>";
		echo "</div><div class=\"hr hr-12 hr-double\"></div>";
		echo "<div style=\"font-size:14px;line-height:30px\">商品信息<br/>";
		echo "<div style=\" float:left\">邮箱：" . $info->email. "</div>";
		echo "<div style=\" margin-left:200px\">状态：" . $info->state.  "</div>"; 
	}
	
	
	/**
	 * #operation=供应商列表修改#
	 */
	public function actionSupplierupdate(){
		if(yii::$app->request->post('action') == 'update'){												//js异步action = update
			$id = yii::$app->request->post('id');
			$supplierModel = new PurchaseForm(['scenario'=>'addsupplier']);
			$model = TbaSupplierinfo::findOne($id);
			
			return $this->renderPartial('updatesupplier',[
					'supplierModel'=>$supplierModel,
					'model'=>$model
			]);
		}
	 	//异步获取助记码
		if(yii::$app->request->post('action') =='supplierab'){
			$name = yii::$app->request->post('name');
			$suppliername = new zhuji();																//实例化助记码类
			$suppliername = strtolower($suppliername->getInitials($name));
			echo $suppliername;exit;
		} 
		if(yii::$app->request->isPost){																	//修改表单有提交动作即进入
			$id = yii::$app->request->post('id');														//获取隐藏域中传过来的ID
			$model = TbaSupplierinfo::findOne($id);														//根据ID查询出该条数据
			$updateModel = new PurchaseForm(['scenario'=>'addsupplier']);								//实例化表单模型
			$updateModel->attributes = yii::$app->request->post('PurchaseForm');				
			$model->attributes = $updateModel->attributes;										
			if($model->update())																		//执行更新动作
				$this->redirect(['purchase/supplier']);
			else 
				exit("<script>alert('失败');window.history.go(-1);</script>");
		}
	}

	
	/**
	 * #operation=供应商列表单条删除#
	 */
	public function actionSupplierdelete(){
		$id = yii::$app->request->post('id');															//获取隐藏域中传过来的ID
		$model = TbaSupplierinfo::findOne($id);															//根据ID查询出该条数据
		if($model->delete()){																			//执行删除动作
			$this->redirect(['purchase/supplier']);
		}
	}
	
	/**
	 * #operation=入库列表异步获取数据操作#
	 */
	public function actionInto(){	
		$start = yii::$app->request->post('start');														//开始的条数
		$length = yii::$app->request->post('length');													//显示的条数
		$column = yii::$app->request->post('order')[0]['column'];										//排序的字段
		$dir = yii::$app->request->post('order')[0]['dir'];												//正序倒叙
		$draw = yii::$app->request->post('draw');														//页数
		$search = yii::$app->request->post('search')['value'];
		
		//允许排序的列
		$columNameArray = [
			'1'=>'id',
			'2'=>'billcode',
			'4'=>'intime',
			'6'=>'intype',
			'9'=>'totalmoney'			
		];		
		$columnName = $columNameArray[$column];
		
		//搜索正则
		if($search)
			$where = "id like '%".$search."%' or billcode like '%".$search."%' or totalmoney like '%".$search."%' or intime like '%".$search."%'";
		else
			$where = '';
		//查询数据库数据
		$model = TmeInstockinfo::find()->where($where)->orderBy($columnName." ".$dir)->limit($length)->offset($start)->all();
		
		$total = TmeInstockinfo::find()->where($where)->count();
		$filtotal = TmeInstockinfo::find()->count();
 		$data =[];
	foreach($model as $v){
		$temp = [];
		$temp['chose']='<td ><label class="pos-rel" style="width:100px;text-align:center"> <input type="checkbox"class="ace" /> <span class="lbl"></span></label></td>';	
		$temp['id']=$v['id'];
		$temp['billcode']=$v['billcode'];
		$merchandiseid = $v->tmeInstockdetailsinfos->merchandiseid;
		$merchandisename = TmeInstockdetailsinfo::find()->where(['merchandiseid'=>$merchandiseid])->one();
		$temp['MerchandiseName']=$merchandisename->tme->MerchandiseName;
		$temp['supplierid']=$v->tba->suppliername;
		$temp['intime']=$v['intime'];
		$temp['handler']=$v['handler'];	
			if($v['intype'] ==0)
				$temp['intype']='正常入库';
			elseif($v['intype'] ==1)
				$temp['intype']='报损';
			elseif($v['intype'] ==2)
				$temp['intype']='报溢';
			else
				$temp['intype']='未知';
		$temp['price']=$v->tmeInstockdetailsinfos->price;
		$temp['totalmoney']=$v['totalmoney'];
		$temp['num']=$v->tmeInstockdetailsinfos->num;
		$temp['operid']=$v->tAu->username;
		$temp['remark']=$v['remark'];
		$temp['options']='<div class="hidden-sm hidden-xs action-buttons">
							<a class="blue" href="#" onclick="return view('.$v['id'].')">
								<i class="ace-icon fa fa-search-plus bigger-130"></i>
							</a>
							<a class="green" href="#" onclick="return update('.$v['id'].')">
								<i class="ace-icon fa fa-pencil bigger-130"></i>
							</a>
							<a class="red"  onclick="return show_confirm('.$v['id'].')" href="#">
								<i class="ace-icon fa fa-trash-o bigger-130"></i>
							</a>				
						</div>';
		$data[] = $temp;
	}

 	$temp = [
	 	'draw'=>$draw,
	 	'recordsTotal'=>$filtotal,													//表的总记录数
	 	'recordsFiltered'=>$total,  											//条件过滤后记录数
	 	'data'=>$data
 	];
 		echo json_encode($temp);					
	}
	
	/**
	 * #operation=入库列表详情查看#
	 */
	public function actionView(){
		$id = yii::$app->request->post('id');									//获取JS中传递过来的ID值
		$info = TmeInstockinfo::findOne($id);
		$detailinfo = TmeInstockdetailsinfo::findOne($id);
		
		if($info->intype ==0)
				$intype='正常入库';
			elseif($info->intype ==1)
				$intype='报损';
			elseif($info->intype ==2)
				$intype='报溢';
			else
				$intype='未知';
		
		echo "<div style=\"font-size:14px;line-height:30px;\"><br/>";
		echo "<div style=\" float:left\">入库单号：" . $info->billcode . "</div>";
		echo "<div style=\" margin-left:200px \">操作员名称：" .$info->tAu->username . "</div>";
		echo "<div style=\" float:left\">供应商名称：".$info->tba->suppliername."</div>";
		echo "<div style=\" margin-left:200px \">入库方式：".$intype."</div>";
		echo "</div><div class=\"hr hr-12 hr-double\"></div>";
		echo "<div style=\"font-size:14px;line-height:30px\">详细信息<br/>";
		echo "<div style=\" float:left\">入库时间：" . $info->intime . "</div>";
		echo "<div style=\" margin-left:200px \">经手人:" . $info->handler . "</div>";
		echo "<div style=\" margin-right:200px \">备注：" . $info->remark. "</div>";
		echo "</div><div class=\"hr hr-12 hr-double\"></div>";
		echo "<div style=\"font-size:14px;line-height:30px\">商品信息<br/>";
		echo "<div style=\" float:left\">单价：" . $detailinfo->price. "</div>";
		echo "<div style=\" margin-left:200px\">数量：" . $detailinfo->num.  "</div>";
		echo "<div style=\" float:left \">金额：" .$info->totalmoney. "</div>";
	}
	/**
	 * #operation=入库列表修改操作#
	 */
	public function actionUpdate(){
					
		$model = new PurchaseForm(['scenario'=>'add']);													//实例化表单模型
		if(yii::$app->request->post('action') == 'ajax_update'){
				$id = yii::$app->request->post('id');													//获取js中传递的id值
				$info = TmeInstockinfo::findOne($id);													//根据id值查询数据					
					$detailinfo = TmeInstockdetailsinfo::findOne($id);									//根据id值查询数据			
				return $this->renderPartial('_purchaseupdate',[											//将数据传入视图
						'id'=>$id,	
						'model'=>$model,
						'info'=>$info,
						'detailinfo'=>$detailinfo
				]);
		}
		//执行修改操作
		if(yii::$app->request->isPost){	
									
			$purModel = new PurchaseForm(['scenario'=>'add']);
			$purModel->attributes = yii::$app->request->post('PurchaseForm');
			$purId = yii::$app->request->post('id');													//获取视图隐藏域中传递过来的ID
			$updateModel = TmeInstockinfo::findOne($purId);												//根据ID值查出要修改的数据行
			$updateModel->handler = $purModel->handler;								
			$updateModel->intype = $purModel->intype;								
			$updateModel->totalmoney = $purModel->num*$purModel->price;									//根据提交的单价和总数量算出总金额
			$updateModel->remark = $purModel->remark;	 						
			$updateModel->update();																		//提交修改
			$update = TmeInstockdetailsinfo::findOne($purId);
			$update->num = $purModel->num;
			$update->price = $purModel->price;	
			//提交修改
			$update->update();		
			$this->redirect(['purchase/index']);
		}
	}
	
	/**
	 * #operation=入库列表单条删除操作#
	 */
	public function actionDelete(){
	    $id = yii::$app->request->post('id');
		$connection = yii::$app->db;
		$stransaction = $connection->beginTransaction();												//开启事务
		 try {
			$model = TmeInstockdetailsinfo::findOne($id);												//根据ID值查询出该行
			if(!$model->delete())
				throw new Exception('删除tme_instockdetailsinfo表有错误',1);
			$model = TmeInstockinfo::findOne($id);
			if(!$model->delete())
				throw new Exception('删除tme_instockinfo有错误',2);
			$stransaction->commit();																	//提交事务
			$this->redirect(['purchase/index']);
		} catch (Exception $e) {				
			$stransaction->rollBack();																	//事务回滚
		}  
	}
	
	
	/**
	 * #operation=入库列表多条删除操作#
	 */
	public function actionDeleteall(){			
			$check = yii::$app->request->post();
			//var_dump($check);exit;
			$this->redirect(['purchase/index']);
	}
	
	/**
	 * #operation=添加库存#
	 */
	public function actionAddinfo(){
		$model = new PurchaseForm(['scenario'=>'addinfo']);
		//商品遍历
		$tmeinstockdetail = TmeMerchandiseinfo::find()->all();
		$merchandisename = ArrayHelper::map($tmeinstockdetail,'MerchandiseID','MerchandiseName');
		//供应商名称遍历
		$tbasupplier = TbaSupplierinfo::find()->all();
		$suppliername = ArrayHelper::map($tbasupplier,'supplierid','suppliername');
		//经手人遍历
		$tmeinstock = TmeInstockinfo::find()->all();
		foreach($tmeinstock as $v){
			$handler[] = $v['handler'];
		}

		return $this->render('addinfo',[
				'model'=>$model,
				'merchandisename'=>$merchandisename,
				'suppliername'=>$suppliername,
				'handler'=>$handler
		]);
	}
	
	/**
	 * #operation=添加库存异步整理数据#
	 */
	public function actionInfofo(){
		
		if(!empty(yii::$app->request->post('action')) && yii::$app->request->post('action') == 'submit'){
			$array = \yii::$app->request->post('data');
			$post =[];
			for($i=1;$i<=10;$i++){
				$num = strpos($array[$i]['name'],'[');
				$name = substr($array[$i]['name'],$num+1,-1);
				$post[$name] = $array[$i]['value'];
			}
			$infoModel = new PurchaseForm(['scenario'=>'addinfo']);
			$infoModel->attributes = $post;
			$infoModel->validate();
			$error = $infoModel->hasErrors();
			$temp['msg'] = $error ? 1 : 0;
			$temp['data'] = $post;
			$temp['data']['id'] = '';
			echo json_encode($temp,true);			
		}	
		
		if(!empty(yii::$app->request->post('action')) && yii::$app->request->post('action') == 'submitAll'){
			$tablesdata = yii::$app->request->post('tablesdata');								//获取添加数据
			$model = new PurchaseForm(['scenario'=>'addinfo']);
			$connection = yii::$app->db;
			foreach($tablesdata as $v){
				$stransaction = $connection->beginTransaction();								//开启事务
				$model->attributes =$v;	
				try{
					$into = new TmeInstockinfo();
					$deinto = new TmeInstockdetailsinfo();
					$operid = $_SESSION['operID'];												//通过session查询operid
					$oper = TauOperinfo::find()->where(['operID'=>$operid])->one();				//根据operid查询tauid
					$tauid = $oper->ID;
					$suppliername = $v['suppliername'];
					$tbasupplier = TbaSupplierinfo::find()->where(['supplierid'=>$suppliername])->one();
					$tba_id = $tbasupplier->id;
					$into->tau_id = $tauid;
					$into->tba_id = $tba_id;
					$into->attributes = $model->attributes;
					$into->supplierid = $suppliername;
					$into->operid = $operid;
					if(!$into->save())
						throw new Exception("插入tme_instockinfo表有错误",1);
					$query = new Query();
					$a = $query->select('id,billcode')->from('tme_instockinfo')->limit(1)->orderBy(['id'=>SORT_DESC])->one();
					$deinto->attributes = $model->attributes;
					$deinto->id =$a['id'];
					$merchname = $model->merchandisename;
					$mer = TmeMerchandiseinfo::find()->where(['MerchandiseID'=>$merchname])->one();
					$tmeid = $mer->ID;
					$deinto->tme_id = $tmeid;
					$deinto->merchandiseid=$merchname;
					if(!$deinto->save())
						throw new Exception("插入tme_instockdetailsinfo表有错误",1);
					$stransaction->commit();													//提交事务
				}catch (Exception $e){								
					$stransaction->rollBack();	
					var_dump($e->getMessage());												//事务回滚
				}
			}
		}
	}
}

?>